<?php
namespace app\admin\controller;

use app\common\controller\AdminBase;
use think\Db;
use think\Exception;
use think\Response;


class Customer extends AdminBase
{
    private $customer_logic;

    public function _initialize()
    {
        parent::_initialize();
        $this->customer_logic = logic('Customer');
    }


    /**
     * 客户列表
     * @return mixed
     */
    public function index()
    {
        $where = [];

        //获取星级评定配置
        $star_level_config_info = model('StarLevelConfig')->getList([])->toArray();
        $star_level_config_info = array_column($star_level_config_info['data'], 'star_level');

        //关键字搜索
        $customer_name = $this->request->param('customer_name', '', 'app\common\controller\ParamFilter::normalParam');
        if (!empty($customer_name)) {
            $where['customer_name'] = $customer_name;
        }

        //税号搜索
        $taxpayer_identity_numbe = $this->request->param('taxpayer_identity_numbe', '', 'app\common\controller\ParamFilter::normalParam');
        if (!empty($taxpayer_identity_numbe)) {
            $where['taxpayer_identity_numbe'] = $taxpayer_identity_numbe;
        }

        //地区
        $province_id = $this->request->param('province_id', 0, 'intval');
        if ($province_id > 0) {
            $where['province_id'] = $province_id;
        }
        $city_id = $this->request->param('city_id', 0, 'intval');
        if ($city_id > 0) {
            $where['city_id'] = $city_id;
        }
        $district_id = $this->request->param('district_id', 0, 'intval');
        if ($district_id > 0) {
            $where['district_id'] = $district_id;
        }

        /*客户编号*/
        $customer_number = $this->request->param('customer_number', '', 'trim');
        if (is_normal_number($customer_number)) {
            $where['customer_number'] = $customer_number;
        }

        //星级
        $star_level = $this->request->param('star_level', 0, 'intval');
        if ($star_level > 0 && in_array($star_level, $star_level_config_info)) {
            $where['star_level'] = $star_level;
        }

        //是否是一般纳税人
        $is_general_taxpayer = $this->request->param('is_general_taxpayer', -1, 'intval');
        if ($is_general_taxpayer == 1 || $is_general_taxpayer == 0) {
            $where['is_general_taxpayer'] = $is_general_taxpayer;
        }

        /*合同签订公司*/
        /*$sign_company_code = $this->request->param('sign_company_code', '', 'trim');
        $sign_company_data = logic('Contract')->getSignCompanyListAndCodeWhere($this->userInfo, $sign_company_code);
        $sign_company_list = $sign_company_data['sign_company_list'];
        $sign_company_code_where = $sign_company_data['sign_company_code_where'];
        if (!empty($sign_company_code_where)) {
            $where['sign_company_code'] = $sign_company_code_where;
        }*/

        //开始时间
        $start = $this->request->param('start', '', '');
        //截止时间
        $end = $this->request->param('end', '', '');

        //处理信息录入时间区间
        if (!empty($start)) {
            $start = strtotime($start);
        } else {
            $start = 0;
        }

        if (!empty($end)) {
            $end = strtotime($end);
        } else {
            $end = 0;
        }

        if ($start > 0) {
            //超过当前时间，强制置为当天
            if ($start > time()) {
                $start = strtotime(date('Y-m-d 00:00:01'), time());
            }

            //避免截止时间比开始时间小或者是同一天的情况
            if ($end < $start) {
                $end = time() + 24*3600;
            }

            //如果是同一天，则设置为当天截止时间
            if ($end == $start) {
                $end = strtotime(date('Y-m-d 23:59:59'), $start);
            }

        }

        $where['start'] = $start;
        $where['end'] = $end;

        $customer_list = $this->customer_logic->getList($where, $this->userInfo, $this->pageLimit);

        return $this->fetch('index', [
            'customer_list' => $customer_list,
            'star_level_config_info' => $star_level_config_info,
            'customer_name' => $customer_name,
            'customer_number' => $customer_number,
            'taxpayer_identity_numbe' => $taxpayer_identity_numbe,
            'star_level' => $star_level,
            'province_id' => $province_id,
            'city_id' => $city_id,
            'district_id' => $district_id,
            'is_general_taxpayer' => $is_general_taxpayer,
            'start' => $start,
            'end' => $end,
            //'sign_company_list' => $sign_company_list,
            //'sign_company_code' => $sign_company_code,
        ]);
    }


    /**
     * 添加人员
     * @return mixed
     */
    public function add()
    {
        $star_level_config = $this->customer_logic->getStarLevelConfig(true);

        if ($this->request->isAjax()) {
            $data = $this->request->post();
            //数据验证
            try {
                $res = $this->customer_logic->submitCustomer($data, $this->userInfo);
                if ($res) {
                    return ajax_return_adv('添加成功！');
                } else {
                    exception('添加失败！');
                }
            } catch (Exception $e) {
                return ajax_return_error($e->getMessage());
            }
        }

        //放入预估编号
        $customer_number = $this->customer_logic->getCustomerNumber();
        $customer_number = $customer_number['customer_number'];

        return $this->fetch('add', [
            'star_level_config' => json_encode($star_level_config['config_info'], JSON_UNESCAPED_UNICODE),
            'star_level_config_doc' => $star_level_config['doc'],
            'customer_number' => $customer_number,
            'software_list' => logic('Config')->getFinancialSoftwareList(),
        ]);
    }


    /**
     * 编辑客户
     * @return mixed
     */
    public function edit()
    {
        $id = $this->request->param('id', 0, 'intval');
        if ($id <= 0) {
            $this->error('请指定客户！');
        }

        $customer_info = $this->customer_logic->getInfo([
            'id' => $id,
        ]);

        //星级配置
        $star_level_config = $this->customer_logic->getStarLevelConfig(true);

        if ($this->request->isAjax() && $id > 0) {
            $data = $this->request->post();
            //数据验证
            try {
                $res = $this->customer_logic->submitCustomer($data, $this->userInfo, $id);
                if ($res) {
                    return ajax_return_adv('修改成功！');
                } else {
                    exception('修改失败！');
                }
            } catch (Exception $e) {
                return ajax_return_error($e->getMessage());
            }
        }

        return $this->fetch('edit', [
            'star_level_config' => json_encode($star_level_config['config_info'], JSON_UNESCAPED_UNICODE),
            'star_level_config_doc' => $star_level_config['doc'],
            'customer_info' => $customer_info,
            'software_list' => logic('Config')->getFinancialSoftwareList(),
        ]);
    }

    /**
     * 删除客户（可批量）
     */
    public function delete()
    {
        $ids = $this->request->param('ids', '', 'trim');
        $ids = explode(',', $ids);
        $ids = array_unique(array_filter(array_map(function($v){
            return (int)$v;
        }, $ids)));

        if ($this->request->isAjax()) {
            if (empty($ids)) {
                return ajax_return_adv('未进行任何删除！');
            }
            Db::startTrans();
            try {
                if (!$this->customer_logic->deleteData($ids)) {
                    exception('请重试');
                }
                Db::commit();
                return ajax_return_adv('删除成功！');
            } catch (Exception $e) {
                Db::rollback();
                return ajax_return_error('删除失败('.$e->getMessage().')！');
            }
        }
    }

    /**
     * 查看客户信息信息
     */
    public function info()
    {
        //全部分组
        $id = $this->request->param('id', 0, 'intval');
        if ($id <= 0) {
            $this->error('请指定客户！');
        }
        $info = $this->customer_logic->getInfo([
            'id' => $id,
        ]);
        return $this->fetch('info', [
            'info' => $info,
        ]);
    }

    /**
     * 通过企查查，查询
     */
    public function selectTIN()
    {

        $company_name = $this->request->param('company_name', '', 'trim');
        if (empty($company_name)) {
            return ajax_return_adv('');
        }

        $url = 'https://www.qichacha.com/tax';

        $header = [
            'Pragma: no-cache',
            'Accept: text/html, application/xhtml+xml, */*',
            'Accept-Language: en-US,zh-CN;q=0.7,en-GB;q=0.3',
            'UA-CPU: AMD64',
            'User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0)',
            'Accept-Encoding: gzip, deflate',
            'Connection: Keep-Alive',
            'Referer: https://www.qichacha.com/tax',
            'Host:  www.qichacha.com',
        ];
        $this->curl_get_https($url, $header);

        $url = "https://www.qichacha.com/tax_search?key={$company_name}";
        $res = $this->curl_get_https($url, $header);

    }

    public function curl_get_https($url, $header, $if_close = false)
    {
        static $ch;
        static $cookie_file;
        if ($ch == null) {
            $ch = curl_init();
        }
        if ($cookie_file == null) {
            $cookie_file = tmpfile();
        }

        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, 0);
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file); //保存cookie到指定文件
        curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file); //使用cookie文件
        curl_setopt($ch, CURLOPT_ENCODING,'gzip');

        //HTTPS
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);  // 从证书中检查SSL加密算法是否存在
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);//设置请求头

        //设置代理
        curl_setopt($ch, CURLOPT_PROXY, '192.168.0.109');
        curl_setopt($ch, CURLOPT_PROXYPORT, 8888);

        // 3. 执行并获取HTML文档内容
        $output = curl_exec($ch);
        file_put_contents('./test.log', $output);
        if($output === FALSE ){
            echo "CURL Error:".curl_error($ch);
        }

        if ($if_close) {
            curl_close($ch);
        }

        return $output;
    }

    /**
     * 列表导出
     */
    public function export_customers()
    {
        $where = [];
        //获取星级评定配置
        $star_level_config_info = model('StarLevelConfig')->getList([])->toArray();
        $star_level_config_info = array_column($star_level_config_info['data'], 'star_level');

        //关键字搜索
        $customer_name = $this->request->param('customer_name', '', 'app\common\controller\ParamFilter::normalParam');
        if (!empty($customer_name)) {
            $where['customer_name'] = $customer_name;
        }

        //税号搜索
        $taxpayer_identity_numbe = $this->request->param('taxpayer_identity_numbe', '', 'app\common\controller\ParamFilter::normalParam');
        if (!empty($taxpayer_identity_numbe)) {
            $where['taxpayer_identity_numbe'] = $taxpayer_identity_numbe;
        }

        //地区
        $province_id = $this->request->param('province_id', 0, 'intval');
        if ($province_id > 0) {
            $where['province_id'] = $province_id;
        }
        $city_id = $this->request->param('city_id', 0, 'intval');
        if ($city_id > 0) {
            $where['city_id'] = $city_id;
        }
        $district_id = $this->request->param('district_id', 0, 'intval');
        if ($district_id > 0) {
            $where['district_id'] = $district_id;
        }

        /*客户编号*/
        $customer_number = $this->request->param('customer_number', '', 'trim');
        if (is_normal_number($customer_number)) {
            $where['customer_number'] = $customer_number;
        }

        //星级
        $star_level = $this->request->param('star_level', 0, 'intval');
        if ($star_level > 0 && in_array($star_level, $star_level_config_info)) {
            $where['star_level'] = $star_level;
        }

        //是否是一般纳税人
        $is_general_taxpayer = $this->request->param('is_general_taxpayer', -1, 'intval');
        if ($is_general_taxpayer == 1 || $is_general_taxpayer == 0) {
            $where['is_general_taxpayer'] = $is_general_taxpayer;
        }


        //开始时间
        $start = $this->request->param('start', '', '');
        //截止时间
        $end = $this->request->param('end', '', '');

        //处理信息录入时间区间
        if (!empty($start)) {
            $start = strtotime($start);
        } else {
            $start = 0;
        }

        if (!empty($end)) {
            $end = strtotime($end);
        } else {
            $end = 0;
        }

        if ($start > 0) {
            //超过当前时间，强制置为当天
            if ($start > time()) {
                $start = strtotime(date('Y-m-d 00:00:01'), time());
            }

            //避免截止时间比开始时间小或者是同一天的情况
            if ($end < $start) {
                $end = time() + 24 * 3600;
            }

            //如果是同一天，则设置为当天截止时间
            if ($end == $start) {
                $end = strtotime(date('Y-m-d 23:59:59'), $start);
            }

        }

        $where['start'] = $start;
        $where['end'] = $end;


        $customer_list = $this->customer_logic->getList($where, $this->userInfo, 20000);
        $customer_list = $customer_list->toArray();


        $file_name = "customer-" . date('ymd');
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="' . $file_name . '.csv"');
        header('Cache-Control: max-age=0');
        header('Set-Cookie: fileDownload=true; path=/');//使用jQuery.fileDownload.js 时必须添加该头，否则会导致回调函数失效

        // 打开PHP文件句柄，php://output 表示直接输出到浏览器
        $fp = fopen('php://output', 'a');

        // 输出Excel列名信息
        $head = [
            '客户编号',
            '客户单位名称',
            '客户单位简称',
            '纳税人识别号',
            '省',
            '市',
            '区/县',
            '具体地址',
            '法定代表人',
            '业务额',
            '星级',
            '主营业务范围',
            '主管税务机关',
            '是否是一般纳税人',
            '财务软件',
            '税收优惠',
            '税务机关专管员',
            '专管员电话',
            '专管员QQ',
            '专管员微信',
            '专管员邮箱',
            '财务副总',
            '财务副总电话',
            '财务副总QQ',
            '财务副总微信',
            '财务副总邮箱',
            '财务经理',
            '财务经理电话',
            '财务经理QQ',
            '财务经理微信',
            '财务经理邮箱',
            '主管会计',
            '主管会计电话',
            '主管会计QQ',
            '主管会计微信',
            '主管会计邮箱',
            '备注',
        ];

        foreach ($head as $i => $v) {
            // CSV的Excel支持GBK编码，一定要转换，否则乱码
            $head[$i] = iconv('utf-8', 'gbk', $v);
        }

        //将数据通过fputcsv写到文件句柄
        fputcsv($fp, $head);


        $count = 0;// 计数器
        $limit = 100000; // 每隔$limit行，刷新一下输出buffer，不要太大，也不要太小

        // 逐行取出数据，不浪费内存
        foreach ($customer_list['data'] as $v) {
            $count++;
            if ($limit == $count) { //刷新一下输出buffer，防止由于数据过多造成问题
                ob_flush();
                flush();
                $count = 0;
            }

            //将每一行数据处理成跟表头对应的形式
            $tmp = $v;
            foreach ($tmp as $k_field => &$v_field) {
                if ($k_field == 'is_general_taxpayer') {
                    $v_field = $v_field ? '是' : '否';
                }

                if ($k_field == 'star_level') {

                    $v_field = $v_field . "星";

                }

                //防止数字被科学计数法显示丢失
                if (is_numeric($v_field) && strlen($v_field) > 8) {
                    $v_field = $v_field."\t";
                }

                $v_field = iconv('utf-8', 'gbk', $v_field);
            }

            $row = [
                $tmp['customer_number'],
                $tmp['company_name'],
                $tmp['short_name'],
                $tmp['taxpayer_identity_numbe'],
                $tmp['province'],
                $tmp['city'],
                $tmp['district'],
                $tmp['address'],
                $tmp['legal_person'],
                $tmp['revenue'],
                $tmp['star_level'],
                $tmp['business_scope'],
                $tmp['tax_bureau'],
                $tmp['is_general_taxpayer'],
                $tmp['financial_software'],
                $tmp['tax_discount'],
                $tmp['tax_bureau_manager'],
                $tmp['tax_bureau_manager_tel'],
                $tmp['tax_bureau_manager_qq'],
                $tmp['tax_bureau_manager_wx'],
                $tmp['tax_bureau_manager_email'],
                $tmp['financial_deputy_majordomo'],
                $tmp['financial_deputy_majordomo_tel'],
                $tmp['financial_deputy_majordomo_qq'],
                $tmp['financial_deputy_majordomo_wx'],
                $tmp['financial_deputy_majordomo_email'],
                $tmp['financial_deputy_manager'],
                $tmp['financial_deputy_manager_tel'],
                $tmp['financial_deputy_manager_qq'],
                $tmp['financial_deputy_manager_wx'],
                $tmp['financial_deputy_manager_email'],
                $tmp['accountant_leader'],
                $tmp['accountant_leader_tel'],
                $tmp['accountant_leader_qq'],
                $tmp['accountant_leader_wx'],
                $tmp['accountant_leader_email'],
                $tmp['note'],
            ];

           fputcsv($fp, $row);
        }
    }

    /**
     * 客户导入使用 Excel模板
     */
    public function import_customers()
    {

        $key = config('admin_upload_key');

        /*合同签订公司*/
        /*$sign_company_code = $this->request->param('sign_company_code', '', 'trim');
        $sign_company_data = logic('Contract')->getSignCompanyListAndCodeWhere($this->userInfo, $sign_company_code);
        $sign_company_list = $sign_company_data['sign_company_list'];*/

        if ($this->request->isPost()) {
            $t      = $this->request->param('t', '');
            $token  = $this->request->param('token', '');

            /*$sign_company_code  = $this->request->param('sign_company_code', '');
            if (empty($sign_company_code)) {
                return ajax_return_error('请指定客户所属的合同签订公司！');
            }

            if (!in_array($sign_company_code, array_column($sign_company_list, 'code'))) {
                return ajax_return_error('请指定正确的合同签订公司！');
            }*/

            if ($token != md5($key . '+' .$t)) {
                return ajax_return_error('error request!');
            }

            ini_set('memory_limit', '520M'); //内存限制
            set_time_limit(0); //超时限制
            $this->request->file();

            try {
                $res= $this->customer_logic->batchImportData($this->userInfo);
                return ajax_return_adv($res);
            } catch (Exception $e) {
                return ajax_return_error($e->getMessage());
            }
        }

        $t = time();
        $batch_token = md5($key . '+' .$t);
        return $this->fetch('import', [
            'token' => $batch_token,
            't'     => $t,
            //'sign_company_list'     => $sign_company_list,
        ]);
    }

    /**
     * 客户列表
     * @return mixed
     */
    public function search()
    {
        if ($this->request->isAjax()) {
            $where = [];

            //关键字搜索
            $customer_name = $this->request->param('customer_name', '', 'app\common\controller\ParamFilter::normalParam');
            if (!empty($customer_name)) {
                $where['customer_name'] = $customer_name;
            }

            /*客户编号*/
            $customer_number = $this->request->param('customer_number', '', 'trim');
            if (is_normal_number($customer_number)) {
                $where['customer_number'] = $customer_number;
            }

            $limit = $this->request->param('limit', 0, 'intval');
            if ($limit <= 0) {
                $limit = $this->pageLimit;
            }

            if ($limit > 1000) {
                $limit = 1000;
            }

            $fields = 'id,customer_number,company_name';
            $customer_list = $this->customer_logic->searchList($where, $fields, $this->userInfo, $limit);

            //处理格式成 layui异步表格需要的形式：（需要和前段设置的一样）
            $ajax_return_data = [
                'code'  => 0,
                'msg'   => "",
                'count' => $customer_list['total'],
                'data'  => $customer_list['data']
            ];
            return $ajax_return_data;//转换成json返回后，反而不行，在layui的table
        }

        return $this->fetch('search');
    }
}
